package com.acme.bankapp.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.server.command.CommandFactory;

public class BankServer {
	public static final int DEFAULT_PORT = 2013;
	private static final int DEFAULT_POOL_SIZE = 10;
	
	ServerSocket providerSocket;
	ExecutorService pool;
	Bank bank;
	CommandFactory cmdFactory;

	public BankServer(Bank bank) throws IOException {
		this.providerSocket = new ServerSocket(DEFAULT_PORT);
		this.pool = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
		this.bank = bank;
		this.cmdFactory = new CommandFactory(bank);
	}

	public void serve() {
		System.out.printf("Starting server on port %d%n",
				providerSocket.getLocalPort());
		try {
			for (;;) {
				pool.execute(new RequestHandler(providerSocket.accept(), cmdFactory));
			}
		} catch (IOException e) {
			e.printStackTrace();
			pool.shutdown();
		} finally {

			try {
				providerSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	public static void main(String[] args) throws IOException {
		Bank bank = new Bank();
		(new BankServer(bank)).serve();
	}
}
